package me.boot.web.common.template.entity;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.Getter;
import lombok.Setter;
import me.boot.db.mybatis.template.entity.AutoEntity;

import java.util.List;
import java.util.stream.Collectors;

@Getter
@Setter
public abstract class BaseTreeEntity<T extends BaseTreeEntity<T>>
        extends BaseNestedEntity<T> implements TreeEntity<T> {

    public abstract Long getParentId();

    public List<Long> getChildrenIds() {
        LambdaQueryWrapper<T> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(T::getId);
        wrapper.eq(T::getParentId, getId());
        List<T> list = getMapper().selectList(wrapper);
        return list.stream().map(AutoEntity::getId).collect(Collectors.toList());
    }

    @Override
    public T getParent() {
        return getMapper().selectById(getParentId());
    }

    @Override
    public List<T> getChildren() {
        return getMapper().selectBatchIds(getChildrenIds());
    }
}
